package collection.mylist;

public class MyLinkedList<E> {
    private int size;
    private Node<E> fist;

    public int size() {
        return size;
    }

    public void add(int index,E element){
        if (index == 0 && fist == null){
            fist = new Node<>(element,null);
        }else {
            linkNode(element,node(index));
        }
        size++;
    }

    private void linkNode(E element, Node<E> node) {
        node.next = new Node<>(element,node.next);
    }

    private Node<E> node(int index) {
        Node<E> last = fist;
        for (int i = 0; i < index-1; i++) {
            last = last.next;
        }
        return last;
    }

    public E set(int index,E element){
        Node<E> node = node(index).next;
        E oldElement = node.item;
        node.item = element;
        return oldElement;
    }
    public E get(int index){
        return node(index).next.item;
    }
    public E remove(int index){
        Node<E> prev = node(index);
        E removeElement = prev.next.item;
        prev.next.item = null;
        prev.next = prev.next.next;
        size--;
        return removeElement;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("MyLinkedList{size=").append(size).append(", elements=[");

        Node<E> current = fist;
        boolean first = true;
        while (current != null) {
            if (!first) {
                sb.append(", ");
            }
            sb.append(current.item);
            current = current.next;
            first = false;
        }

        sb.append("]}");
        return sb.toString();
    }


    private static class Node<E>{
        E item;
        Node<E> next;

        public Node(E item, Node<E> next) {
            this.item = item;
            this.next = next;
        }
    }
}
